package com.yijiajiao.finance.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yijiajiao.finance.bean.*;
import com.yijiajiao.finance.mappers.IOSMoneyChangeMapper;
import com.yijiajiao.finance.mappers.IOSMoneyMapper;
import com.yijiajiao.finance.service.IOSMoneyService;
import com.yijiajiao.finance.util.Config;
import com.yijiajiao.finance.util.DateUtil;
import com.yijiajiao.finance.util.HttpUtil;
import com.yijiajiao.finance.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * @AUTHOR zhaoming@eduspace
 * @CREATE 2017-02-14-14:31
 */
@Slf4j
@Service("iosMoneyService")
public class IOSMoneyServiceImpl implements IOSMoneyService {
    @Autowired
    private IOSMoneyMapper iosMoneyMapper;
    @Autowired
    private IOSMoneyChangeMapper iosMoneyChangeMapper;

    @Override
    @Transactional
    public ResultBean addIOSMoney(IOSMoneyBean iosMoneyBean) {
        //内购二次验证
        Map<String,Object> bodyParam = new HashMap<>();
        bodyParam.put("receipt-data", iosMoneyBean.getReceipt());
        String response = HttpUtil.httpRest("", Config.getString("ProductionUrl"),null,bodyParam, "POST");
        JSONObject resultObject = JSON.parseObject(response);
        int status = resultObject.getInteger("status");
        if (status!=0 && status!=21007){
            log.error("苹果内购二次验证出错：status="+status);
            return ResultBean.getFailResult(status,"苹果内购二次验证时出错:status="+status);
        } else if (21007 == status){
            log.info("receipt是测试环境验证码，请求Sandbox==>");
            response = HttpUtil.httpRest("", Config.getString("SandboxUrl"), null, bodyParam, "POST");
            resultObject = JSON.parseObject(response);
        }
        JSONObject receipt = JSON.parseObject(resultObject.getString("receipt"));
        List<InAppBean> inAppBeens = JSON.parseArray(receipt.getString("in_app"), InAppBean.class);
        InAppBean iab = inAppBeens.get(inAppBeens.size()-1);//取数组最后一个实例数据
        String[] split = StringUtil.split(iab.getProduct_id(), ".");
        BigDecimal addMoney = new BigDecimal(split[split.length-1]);
        IOSMoney money = iosMoneyMapper.getByOpenId(iosMoneyBean.getOpenId());
        //添加或者修改ios_money账户
        if (money == null){
            money = IOSMoney.builder()
                    .openId(iosMoneyBean.getOpenId())
                    .money(addMoney)
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build();
            log.info("不存在"+iosMoneyBean.getOpenId()+"账户，添加信息：\n _"+money);
            iosMoneyMapper.addMoneyAccount(money);
        }else {
            money.setMoney(money.getMoney().add(addMoney));
            money.setUpdateTime(new Date());
            log.info("修改("+money.getOpenId()+")账户信息：\n _"+money);
            iosMoneyMapper.updateMoney(money);
        }
        //添加充值记录
        IOSMoneyChange change = IOSMoneyChange.builder()
                .openId(iosMoneyBean.getOpenId())
                .transactionId(iab.getTransaction_id())
                .moneyChange(addMoney)
                .type(1)
                .time(new Date())
                .build();
        log.info("【添加充值记录】，信息："+change);
        iosMoneyChangeMapper.add(change);
        return ResultBean.getSucResult("充值成功!");
    }

    @Override
    public ResultBean queryRemainMoney(String openId) {
        if (StringUtil.isEmpty(openId)){
            return ResultBean.getFailResult(SystemStatus.ID_NOT_FOUND);
        }
        IOSMoney money = iosMoneyMapper.getByOpenId(openId);
        log.info("用户("+openId+")的账号信息：\n __"+money);
        double remainMoney = 0.00;
        if (money != null) remainMoney = money.getMoney().doubleValue();
        Map<String,Object> remain = new HashMap<>();
        remain.put("openId",openId);
        remain.put("remainMoney",remainMoney);
        return ResultBean.getSucResult(remain);
    }

    @Override
    @Transactional
    public ResultBean consumeMoney(IOSMoneyBean iosMoneyBean) {
        BigDecimal moneyChange = new BigDecimal(iosMoneyBean.getMoney());
        IOSMoney money = iosMoneyMapper.getByOpenId(iosMoneyBean.getOpenId());
        if (money == null || money.getMoney().compareTo(moneyChange)==-1){
            return ResultBean.getFailResult(SystemStatus.REMAIN_NOT_ENOUGH);
        }
        money.setMoney(money.getMoney().subtract(new BigDecimal(iosMoneyBean.getMoney())));
        money.setUpdateTime(new Date());
        log.info("修改("+money.getOpenId()+")账户信息：\n _"+money);
        iosMoneyMapper.updateMoney(money);
        //添加充值记录
        IOSMoneyChange change = IOSMoneyChange.builder()
                .openId(iosMoneyBean.getOpenId())
                .transactionId(iosMoneyBean.getTransactionId())
                .moneyChange(new BigDecimal(iosMoneyBean.getMoney()))
                .type(0)
                .time(new Date())
                .build();
        log.info("【添加消费记录】，信息："+change);
        iosMoneyChangeMapper.add(change);
        String path = Config.getString("sale.updateOrderStatus")+"orderNumber="+iosMoneyBean.getTransactionId()+"&status="+2;
        String response = HttpUtil.httpRest(Config.getString("sale_server"), path, null, null, "PUT");
        ResultBean result = JSON.parseObject(response, ResultBean.class);
        if (result.getCode()!=200){
            throw new RuntimeException("sale_server_exception:"+result.getMessage());
        }
        return ResultBean.getSucResult("支付成功!");
    }

    @Override
    public ResultBean transList(String openId, Integer type, int pageNo, int pageSize) {
        Map<String,Object> param = new HashMap<>();
        param.put("openId",openId);
        param.put("type",type);
        if (pageNo != 0){
            param.put("startRow",(pageNo-1)*pageSize);
            param.put("pageSize",pageSize);
        }
        int count = iosMoneyChangeMapper.count(param);
        List<IOSMoneyChange> list = iosMoneyChangeMapper.listByOpenId(param);
        if (list == null) list = new ArrayList<>();
        Page<IOSMoneyChange> page = new Page<>(pageNo,pageSize,count,list);
        return ResultBean.getSucResult(page);
    }

    @Override
    @Transactional
    public ResultBean delByIds(String ids) {
        String[] _ids = StringUtil.split(ids, ",");
        iosMoneyChangeMapper.delByIds(_ids);
        return ResultBean.getSucResult("删除成功!");
    }

}
